package www.ym.com.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import www.ym.com.common.CustomException;
import www.ym.com.common.R;
import www.ym.com.entity.menu.Menu;
import www.ym.com.service.MenuService;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @GetMapping("/list")
    public R<List<Menu>> menuList(){
        List<Menu> list = menuService.list();
      return  R.success(list,"");
    }

    /**
     * 新增菜单(一级或二级)
     * @param menu
     * @return
     */
    @PostMapping("addMenu")
    public R<String> addMenu(@RequestBody Menu menu){
        log.info("menu+"+menu);
        menu.setType(0);
        menuService.save(menu);
        return R.success("","新增成功");
    }

    /**
     * 修改菜单(一级或二级)
     * @param menu
     * @return
     */
    @PostMapping("/updateMenu")
    public R<String> upMenu(@RequestBody Menu menu){
        menuService.updateById(menu);
        return R.success("","修改成功");
    }

    /**
     * 删除菜单
     * @param id
     * @return
     */
    @DeleteMapping("/delMenu")
    public R<String> delMenu( Long id){
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
         wrapper.eq(Menu::getParentId, id);
        int count = menuService.count(wrapper);
        //判断是否一级菜单
        if(count>0){
            new CustomException("删除失败，菜单已关联二级菜单");
        }
        menuService.removeById(id);
        return R.success("","删除成功");
    }

}
